#!/bin/bash

# 数据库备份脚本
# 用法: ./backup-db.sh [backup_name]

# 加载环境变量
set -a
source ../.env
set +a

# 设置变量
BACKUP_DIR="../backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME=${1:-"backup_${DATE}"}
DB_NAME=${DATABASE_NAME:-"aicet"}
DB_USER=${DATABASE_USER:-"postgres"}
DB_HOST=${DATABASE_HOST:-"localhost"}
DB_PORT=${DATABASE_PORT:-"5432"}

# 创建备份目录
mkdir -p "$BACKUP_DIR"

echo "📦 开始备份数据库..."
echo "• 数据库: $DB_NAME"
echo "• 文件名: $BACKUP_NAME"

# 执行备份
PGPASSWORD=$DATABASE_PASSWORD pg_dump \
  -h "$DB_HOST" \
  -p "$DB_PORT" \
  -U "$DB_USER" \
  -F c \
  -b \
  -v \
  -f "$BACKUP_DIR/${BACKUP_NAME}.backup" \
  "$DB_NAME"

if [ $? -eq 0 ]; then
  echo "✅ 备份完成! 文件保存在: $BACKUP_DIR/${BACKUP_NAME}.backup"
else
  echo "❌ 备份失败!"
  exit 1
fi
